package com.fins.gt.util;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;


import com.fins.gt.model.ColumnInfo;
import com.fins.gt.model.FilterInfo;
import com.fins.gt.model.GridInfo;
import com.fins.gt.model.PageInfo;
import com.fins.gt.model.SortInfo;


public class ModelUtils {
	
	public static GridInfo createGridInfo(JsonNode modelJS){
		GridInfo info = new GridInfo();
		info.setId(modelJS.get("id").getTextValue());
		return info;
	}
		
	public static ColumnInfo createColumnInfo(JsonNode modelJS){
		ColumnInfo info=new ColumnInfo();
		info.setId(modelJS.get("id").getTextValue());
		info.setHeader(modelJS.get("header").getTextValue());
		info.setFieldIndex(modelJS.get("fieldIndex").getTextValue());
		info.setSortOrder(modelJS.get("sortOrder").getTextValue());
		
		info.setHidden((Boolean)modelJS.get("hidden").getBooleanValue());
		info.setExportable((Boolean)modelJS.get("exportable").getBooleanValue());
		info.setPrintable((Boolean)modelJS.get("printable").getBooleanValue());
		return info;
	}
	//主要修改这个方法---这个应该是初始化全部置为-1
	public static PageInfo createPageInfo(JsonNode modelJS){
		PageInfo info=new PageInfo();
		info.setEndRowNum(modelJS.get("endRowNum").getIntValue());
		info.setPageNum(modelJS.get("pageNum").getIntValue());
		info.setPageSize(modelJS.get("pageSize").getIntValue());
		info.setStartRowNum(modelJS.get("startRowNum").getIntValue());
		info.setTotalPageNum(modelJS.get("totalPageNum").getIntValue());
		info.setTotalRowNum(modelJS.get("totalRowNum").getIntValue());
		return info;
	}
	//-----------------------为增加方法------------------------------------------------
	  /* wzj    */
    public int getIntForPage(String key,int ifNull) {
        Object o = get(key);
        if (o==null) return ifNull;
        return o instanceof Number ?
                ((Number)o).intValue() : (int)getDouble(key);
    }
    
    /**
     * Get the value object associated with a key.
     *
     * @param key   A key string.
     * @return      The object associated with the key.
     * @throws   JSONException if the key is not found.
     */
    public Object get(String key) {
        Object o = opt(key);
        if (o == null) {
            //throw new JSONException("JSONObject[" + quote(key) +"] not found.");
        }
        return o;
    }
    
    private Map map;
    
    /**
     * Get an optional value associated with a key.
     * @param key   A key string.
     * @return      An object which is the value, or null if there is no value.
     */
    public Object opt(String key) {
        return key == null ? null : this.map.get(key);
    }

    
    /**
     * Get the double value associated with a key.
     * @param key   A key string.
     * @return      The numeric value.
     * @throws Exception 
     * @throws JSONException if the key is not found or
     *  if the value is not a Number object and cannot be converted to a number.
     *  修改了这个方法
     */
    public double getDouble(String key){
        Object o = get(key);
        try {
            return o instanceof Number ?
                ((Number)o).doubleValue() :
                Double.valueOf((String)o).doubleValue();
        } catch (Exception e) {
        	//System.out.println("e-- "+e);
            //throw new JSONException("JSONObject[" + ModelUtils.quote(key) +"] is not a number.");
        	 return 0;
        }
       
    }
    
    /**
     * Produce a string in double quotes with backslash sequences in all the
     * right places. A backslash will be inserted within </, allowing JSON
     * text to be delivered in HTML. In JSON text, a string cannot contain a
     * control character or an unescaped quote or backslash.
     * @param string A String
     * @return  A String correctly formatted for insertion in a JSON text.
     */
    public static String quote(String string) {
        if (string == null || string.length() == 0) {
            return "\"\"";
        }

        char         b;
        char         c = 0;
        int          i;
        int          len = string.length();
        StringBuffer sb = new StringBuffer(len + 4);
        String       t;

        sb.append('"');
        for (i = 0; i < len; i += 1) {
            b = c;
            c = string.charAt(i);
            switch (c) {
            case '\\':
            case '"':
                sb.append('\\');
                sb.append(c);
                break;
            case '/':
                if (b == '<') {
                    sb.append('\\');
                }
                sb.append(c);
                break;
            case '\b':
                sb.append("\\b");
                break;
            case '\t':
                sb.append("\\t");
                break;
            case '\n':
                sb.append("\\n");
                break;
            case '\f':
                sb.append("\\f");
                break;
            case '\r':
                sb.append("\\r");
                break;
            default:
                if (c < ' ' || (c >= '\u0080' && c < '\u00a0') ||
                               (c >= '\u2000' && c < '\u2100')) {
                    t = "000" + Integer.toHexString(c);
                    sb.append("\\u" + t.substring(t.length() - 4));
                } else {
                    sb.append(c);
                }
            }
        }
        sb.append('"');
        return sb.toString();
    }
    
    //-----------------------------以上注释为注释方法----------------------------------------------------------
    /***/
	public static String generatePageInfoJSON(PageInfo pageInfo){
		System.out.println("generatePageInfoJSON=== "+pageInfo);
		ObjectMapper mapper = new ObjectMapper();
		StringWriter sw = new StringWriter();  
		JsonGenerator gen;
		try {
			gen = new JsonFactory().createJsonGenerator(sw);
			mapper.writeValue(gen, pageInfo);  
			gen.close();  
		} catch (IOException e) {
			e.printStackTrace();
		}  
		String finalInfo = sw.toString();  
		System.out.println("finalinfo is:"+finalInfo );  
		return finalInfo;
	}
	
	public static SortInfo createSortInfo(JsonNode modelJS){
		SortInfo info=new SortInfo();

		info.setColumnId(modelJS.get("columnId").getTextValue());
		info.setFieldName(modelJS.get("fieldName").getTextValue());
		info.setSortOrder(modelJS.get("sortOrder").getTextValue());
		System.out.println("columnId---- "+info.getColumnId());
		return info;
	}
	//过滤
	public static FilterInfo createFilterInfo(JsonNode modelJS){
		FilterInfo info=new FilterInfo();
		
		//info.setColumnId(modelJS.get("columnId").getTextValue() );//暂时把这个注释掉
		info.setFieldName(modelJS.get("fieldName").getTextValue() );
		info.setLogic(modelJS.get("logic").getTextValue() );
		info.setValue(modelJS.get("value").getTextValue() );
		
		return info;
	}
	/**
	//----------------------增加这个转换方法--------------------------------
	public static Map JSONObject2Map(JSONObject obj_JS){
		Map map=new HashMap();
		Iterator keyItr= obj_JS.keys();
		while(keyItr.hasNext()){
			String key=(String)keyItr.next();
			Object e;
			try {
				e = obj_JS.get(key);
				if (e instanceof JSONObject){
					e = JSONObject2Map((JSONObject)e);
				}
				map.put(key,e);
			} catch (JSONException e1) {}
			
		}
		
		return map;
	}
	
	*/

}
